<template>
  <div class="container">
    <h1>管理员登录</h1>
    <el-form ref="formRef" :model="admin" label-width="60px" status-icon>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="admin.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="admin.password"></el-input>
      </el-form-item>
      <el-form-item label="验证码">
        <el-input type="text" v-model="admin.captchaInput"></el-input>
        <el-image style="width: 120px; height: 38px" :src="imageBase64Data" @click="getCaptcha"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import adminApi from '@/api/adminApi.js';
import {ref} from 'vue';
import {ElMessage} from 'element-plus';
import router from '@/router';
import {useTokenStore} from '@/stores/token.js';

const tokenStore = useTokenStore();

const admin = ref({
  username: '',
  password: '',
  key: '',
  captchaInput: ''
});

const imageBase64Data = ref('');

function login() {
  adminApi.login(admin.value)
      .then(resp => {
        if (resp.code === 10000) {
          //弹出提示信息
          ElMessage.success({
            message: resp.msg,
            duration: 1200,
            onClose: () => {
              tokenStore.updateToken(resp.data);
              router.push('/admin/index');
            }
          });
        } else {
          ElMessage.error(resp.msg);
        }
      })
}

function getCaptcha() {
  adminApi.captcha()
      .then(resp => {
        admin.value.key = resp.data.key;
        imageBase64Data.value = resp.data.imageBase64Data;
      });
}

getCaptcha();
</script>

<style scoped>
.container {
  width: 300px;
  border: 1px solid black;
  border-radius: 5px;
  padding: 20px;
  padding-top: 0px;
  margin: auto;
  margin-top: 150px;
  background-color: lightskyblue;
  background-image: url("pic/f.png");
  background-size: cover;
  background-position: center;

}
</style>
